//
//  TimelineViewModel.swift
//  01sinablog
//
//  Created by ZhangZiang on 15/12/21.
//  Copyright © 2015年 ZhangZiang. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class TimelineViewModel: NSObject {

    
    class func loadHomeViewData(since_id : Int64, max_id : Int64, finished : (timelineList : [Timeline]?) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //        let AFN = AFHTTPSessionManager()
        
        guard let token = UserAccountViewModel().userAccount?.access_token else
        {
            SVProgressHUD.showInfoWithStatus("请重新登录")
            
            return
        }
        
        var parameters = ["access_token" : token]
        
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"//需要-1,要不最后一条会重复出现
        }
        
        NetworkTool.sharedNetworkTool.requestJSONDict(.GET, parameters: parameters, urlString: urlString) { (dict, error) -> () in
            if error != nil
            {
                SVProgressHUD.showErrorWithStatus("网不给力")
                return
            }
            //取得想要的字典数组
            if let array = dict!["statuses"] as? [[String : AnyObject]]//数组里是字典
            {
                var list = [Timeline]()
                for dictStatuse in array
                {
                    //字典转模型
                    let timeline = Timeline(dict : dictStatuse)
                    list.append(timeline)
                   
                }
  
//                finished(timelineList: list)
                //用群组异步,单张图片都下载完后再回调
                cacheSingleImage(list, finished: finished)
            }
            
        }
    }
    //MARK: 群组异步  这样加载单张图片可以实现不同图片size不同
    class func cacheSingleImage(list : [Timeline], finished : (timelineList : [Timeline]?) -> ()) {
        
        if list.count == 0 {
            finished(timelineList: list)
            return
        }
        
        //1.创建组
        let group = dispatch_group_create()
        //2.把所有单张图片都加入组监听中
        for timeline in list {
            //不是单张图片就跳过此次循环
           if let urls = timeline.imageURLs where urls.count != 1 {
            
                continue
            }
           
            //2.1 入组
            dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(timeline.imageURLs?.last, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                //单张图片下载完毕
                //2.2 出组 (有入就要有出)
                dispatch_group_leave(group)
            })
        }
        //3.群组监听
        //群组中的任务数为0的时候会触发事件
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            finished(timelineList: list)
        }
    }
}


